package cn.iocoder.yudao.module.gov.service.resourcedirectory;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.db.Page;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import cn.iocoder.yudao.module.gov.controller.admin.resourcedirectory.vo.*;
import cn.iocoder.yudao.module.gov.dal.dataobject.resourcedirectory.ResourceDirectoryDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.gov.dal.mysql.resourcedirectory.ResourceDirectoryMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getPortalLoginUserId;


/**
 * 政务资源目录 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class ResourceDirectoryServiceImpl implements ResourceDirectoryService {

    @Resource
    private ResourceDirectoryMapper resourceDirectoryMapper;

    @Override
    public Long createResourceDirectory(ResourceDirectorySaveReqVO createReqVO) {
        // 插入
        ResourceDirectoryDO resourceDirectory = BeanUtils.toBean(createReqVO, ResourceDirectoryDO.class);
        resourceDirectoryMapper.insert(resourceDirectory);

        // 返回
        return resourceDirectory.getCatalogId();
    }

    @Override
    public void updateResourceDirectory(ResourceDirectorySaveReqVO updateReqVO) {
        // 更新
        ResourceDirectoryDO updateObj = BeanUtils.toBean(updateReqVO, ResourceDirectoryDO.class);
        resourceDirectoryMapper.updateById(updateObj);
    }

    @Override
    public void deleteResourceDirectory(Long id) {
        // 删除
        resourceDirectoryMapper.deleteById(id);
    }

    @Override
        public void deleteResourceDirectoryListByIds(List<Long> ids) {
        // 删除
        resourceDirectoryMapper.deleteByIds(ids);
        }



    @Override
    public ResourceDirectoryDO getResourceDirectory(Long id) {
        return resourceDirectoryMapper.selectById(id);
    }

    @Override
    public PageResult<ResourceDirectoryDO> getResourceDirectoryPage(ResourceDirectoryPageReqVO pageReqVO) {
        return new PageResult<>(
                resourceDirectoryMapper.selectPage01List(pageReqVO),
                resourceDirectoryMapper.selectPage01Count(pageReqVO)
        );
    }

    @Override
    public PageResult<ResourceDirectoryDO> getInterfacePageList(ResourceDirectoryPageReqVO pageReqVO) {
        return new PageResult<>(
                resourceDirectoryMapper.getInterfacePageList(pageReqVO),
                resourceDirectoryMapper.getInterfaceCount(pageReqVO)
        );
    }

    @Override
    public void collect(Long catalogId) {
        resourceDirectoryMapper.toggleCollect(catalogId, getPortalLoginUserId());
    }

    @Override
    public List<ResourceDirectoryDO> getResourceDirectoryTop(ResourceDirectoryPageReqVO pageReqVO) {
        return resourceDirectoryMapper.selectPage01List(pageReqVO);
    }

    @Override
    public List<ResourceDirectoryDO> getInterfacePageTop(ResourceDirectoryPageReqVO pageReqVO) {
        return resourceDirectoryMapper.getInterfacePageList(pageReqVO);
    }


    @Override
    public int deleteAll() {
       return resourceDirectoryMapper.deleteAll();
    }

    @Override
    public void saveBatch(List<ResourceDirectoryDO> directoryList) {
        resourceDirectoryMapper.insertBatch(directoryList);
    }

    @Override
    public void updateResourceDirectoryStatus(Long catalogId, String status) {
        // 先确保记录存在（原子操作）
        ensureResourceDirectoryExtExists(catalogId);
        // 更新状态
        resourceDirectoryMapper.updateResourceDirectoryStatus(catalogId, status);
    }

    //添加目录浏览量
    @Override
    public void addPageView(Long catalogId) {
        // 先确保记录存在（原子操作）
        ensureResourceDirectoryExtExists(catalogId);
        // 增加浏览量
        resourceDirectoryMapper.updatePageView(catalogId);
    }

    /**
     * 给目录绑定接口
     * @param catalogId
     * @param infoId
     */
    @Override
    public void Interface(Long catalogId, String infoId) {
        // 先确保记录存在（原子操作）
        ensureResourceDirectoryExtExists(catalogId);
        //绑定接口
        resourceDirectoryMapper.updateInterface(catalogId, infoId);
    }



    /**
     * 确保扩展表记录存在，解决并发插入问题
     * 采用达梦数据库支持的 MERGE INTO 语法实现原子操作
     */
    private void ensureResourceDirectoryExtExists(Long catalogId) {
        try {
            // 调用 MERGE 操作，存在则不处理，不存在则插入
            resourceDirectoryMapper.mergeResourceDirectoryExt(catalogId);
        } catch (Exception e) {
            throw new RuntimeException("操作资源目录扩展表失败", e);
        }
    }


    @Override
    public List<ResourceDirectoryDO> getResourceDirectoryAll() {
        return resourceDirectoryMapper.selectList();
    }




}